package org.finesys.common.security.core.fegin;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.finesys.common.constants.SecurityConstants;
import org.finesys.common.core.util.WebUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.server.resource.web.BearerTokenResolver;
import org.springframework.util.Base64Utils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;

import static org.finesys.common.constants.BaseConstant.GATEWAY_TOKEN_HEADER;
import static org.finesys.common.constants.BaseConstant.GATEWAY_TOKEN_VALUE;

/**
 * feign增强
 */
public class AuthRequestInterceptor implements RequestInterceptor {

    private final BearerTokenResolver bearerTokenResolver;

    public AuthRequestInterceptor(BearerTokenResolver bearerTokenResolver) {
        this.bearerTokenResolver = bearerTokenResolver;
    }

    @Override
    public void apply(RequestTemplate requestTemplate) {
        String gatewayToken = new String(Base64Utils.encode(GATEWAY_TOKEN_VALUE.getBytes()));
        requestTemplate.header(GATEWAY_TOKEN_HEADER, gatewayToken);
        Collection<String> fromHeader = requestTemplate.headers().get(SecurityConstants.FROM);
        // 带from 请求直接跳过
        if (!ObjectUtils.isEmpty(fromHeader) && fromHeader.contains(SecurityConstants.FROM_IN)) {
            return;
        }
        // 非web 请求直接跳过
        if (!WebUtil.getRequest().isPresent()) {
            return;
        }
        HttpServletRequest request = WebUtil.getRequest().get();
        //避免请求参数的query token无法传递
        String token = bearerTokenResolver.resolve(request);
        if (!StringUtils.hasLength(token)) {
            return;
        }
        //加入token
        requestTemplate.header(HttpHeaders.AUTHORIZATION, String.format("%s %s", OAuth2AccessToken.TokenType.BEARER.getValue(), token));
    }
}
